package com.zhj.juc.demo2;

/**
 * @PackageName:com.zhj.juc.demo2
 * @ClassName:Test1
 * @auter: 朱慧杰
 * @date:2020/7/23 0023 8:58
 **/
public class Test1 {

    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"D").start();
    }

}

class Data {

    private int number = 0;

    public synchronized void increment() {

        // if 改 while 解决 虚假唤醒
        while (number!=0) {
            // 等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number++;
        System.out.println(Thread.currentThread().getName() + " => " + number);
        // 通知其他线程
        this.notifyAll();
    }

    public synchronized void decrement() {

        while (number==0) {
            // 等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        System.out.println(Thread.currentThread().getName() + " => " + number);
        // 通知其他线程
        this.notifyAll();
    }
}